package com.carme.generator;

import cn.org.rapid_framework.generator.*;
import cn.org.rapid_framework.generator.Generator;
import cn.org.rapid_framework.generator.GeneratorFacade;
import cn.org.rapid_framework.generator.provider.db.table.TableFactory;
import cn.org.rapid_framework.generator.provider.db.table.model.Table;
import com.carme.generator.constants.PropertyConstant;
import com.carme.generator.util.GeneratorUtil;

import java.util.List;

/**
 * 代码生成工厂
 * Created by admin on 2016/3/7.
 */
public class GeneratorFactory {

    private static GeneratorFactory factory = null;
    private GeneratorFacade facade = null;

    public GeneratorFactory(){
        facade= new GeneratorFacade();
    }

    public static GeneratorFactory getInstance(){
        if(factory==null){
            factory = new GeneratorFactory();
        }
        return factory;
    }

    public void create() throws Exception{

            cn.org.rapid_framework.generator.Generator generator = new Generator();
            generator.setOutRootDir("output");
            generator.setTemplateRootDir("template");
            facade.setGenerator(generator);

            // 刪除输出目录
            facade.deleteOutRootDir();

            // 全表生成
            String allSwitch = GeneratorProperties.getProperty(PropertyConstant.ALL_SWITCH);
            if("true".equals(allSwitch)){
                List<Table> tables =  TableFactory.getInstance().getAllTables();
                for (Table table:tables){
                    GeneratorUtil.removeTablePrefix(table,GeneratorProperties.getProperty(PropertyConstant.PREFIX).split(","));
                    Generator.GeneratorModel models = GeneratorFacade.GeneratorModelUtils.newGeneratorModel("table", table);
                    facade.generateBy(models);
                }
            }

            // 根据表结构生成代码
            if("false".equals(allSwitch)){
                if(!"".equals(GeneratorProperties.getProperty(PropertyConstant.TABLES)) || null != GeneratorProperties.getProperty(PropertyConstant.TABLES)) {
                    String[] tableNames = GeneratorProperties.getProperty(PropertyConstant.TABLES).split(",");
                    Table table = null;

                    for (String tableName :tableNames) {
                        table =  TableFactory.getInstance().getTable(tableName);
                        GeneratorUtil.removeTablePrefix(table,GeneratorProperties.getProperty(PropertyConstant.PREFIX).split(","));
                        Generator.GeneratorModel models = GeneratorFacade.GeneratorModelUtils.newGeneratorModel("table", table);
                        facade.generateBy(models);
                    }
                }else{
                    throw new RuntimeException(PropertyConstant.TABLES + "值不存在");
                }
            }
    }


}
